import React from 'react';
import { Button, Form, Input, message } from 'antd';
import './login.less'
import {adminLogin} from '@/api/admin'
import store from 'store2';
import {useDispatch} from 'react-redux'
import {useNavigate} from 'react-router-dom'
import {changeLoginState,changeAdminname,changeToken,changeRole,changeCheckedKeys} from '@/store/modules/admin'
const Login = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const onFinish = (values) => {  // values={adminname:,password}
    // console.log('Success:', values);
    adminLogin(values).then(res=>{
      switch(res.data.code){
        case '10005':
          message.error('账户不存在！')
          break;
        case '10003':
          message.error('密码输入错误！')
          break;
        default:
          message.success('登录成功！')
          // 信息存储到本地 （做持久化）
          const result = res.data.data
          store.set('users',{
            loginState:true,
            token:result.token,
            adminname:result.adminname,
            role:result.role,
            checkedKeys:result.checkedkeys
          })

          // 更新redux的状态
          dispatch(changeLoginState(true))
          dispatch(changeAdminname(result.adminname))
          dispatch(changeToken(result.token))
          dispatch(changeRole(result.role))
          dispatch(changeCheckedKeys(result.checkedkeys))

          // 编程式导航跳转到首页  push vs replace跳转  
          navigate('/',{replace:true})  
      }
    })
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <div className="login">
      <div className="login-box">
        <h3>嗨购后台管理系统</h3>
        <Form
          name="basic"
          initialValues={{
            adminname:'admin',
            password:'123456'
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="adminname"
            name="adminname"
            rules={[
              {
                required: true,
                message: 'Please input your adminname!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="password"
            name="password"
            rules={[
              {
                required: true,
                message: 'Please input your password!',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item>
            <Button className='login-btn' type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
export default Login;